package com.shun.service

import com.shun.commons.ApiUtils
import com.shun.commons.exception.ApiException
import com.shun.entity.Company
import com.shun.entity.Machine
import com.shun.entity.Point
import com.shun.entity.User
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.stereotype.Service
import java.util.*

/**
 * Created by rainbow on 2017/9/5.
 *一事专注，便是动人；一生坚守，便是深邃！
 */
@Service
class CompanyService {

    @Autowired
    private lateinit var mongoTemplate: MongoTemplate

    @Autowired
    private lateinit var utils: ApiUtils

    fun create(user: User, params: Company) {
        val company = Company()

        var temp: Machine? = null

        if (params.machineCode!!.isNotBlank()) {
            temp = mongoTemplate.findOne(Query.query(Criteria("machineCode").`is`(params.machineCode)), Machine::class.java) ?: throw ApiException("编码为${params.machineCode}的设备不存在")
        }
//        val info = mongoTemplate.findOne(Query.query(Criteria("machineCode").`is`(params.machineCode)), Company::class.java)
//        if (info != null) throw ApiException("设备编码为${params.machineCode}的设备已经绑定到其它商家")
        company.machine = temp
        company.desc = params.desc
        company.user = user
        company.name = params.name
        company.status = 1
        company.uuid = UUID.randomUUID().toString()
        company.mobile = params.mobile
        company.username = params.username
        company.searchKey = build(company)
        company.machineCode = params.machineCode
        company.code = params.code


        company.address = params.address


        mongoTemplate.insert(company)

    }

    fun list(params: Map<String, Any?>): Any {
        val criteria = Criteria()

        if (params["searchKey"].toString().isNotBlank()) criteria.and("searchKey").regex(params["searchKey"].toString())

        if (params["status"].toString().isNotBlank()) criteria.and("status").`in`(params["status"].toString().split(",").map(String::toInt))
        val query = Query.query(criteria)

        val page = if (params["page"] != null) params["page"].toString().toInt() else 0
        val size = if (params["size"] != null) params["size"].toString().toInt() else 10


        if (page > 0) {
            query.skip((page - 1) * size).limit(size)
        }

        val list = mongoTemplate.find(query, Company::class.java)

        return if (page > 0) {
            mapOf(
                    "list" to list,
                    "page" to page,
                    "size" to size,
                    "total" to mongoTemplate.count(query, Company::class.java)
            )
        } else {
            list
        }
    }


    //根据searchKey模糊匹配商户
    fun getCompany(searchKey: String): List<Company>? = mongoTemplate.find(Query.query(Criteria("searchKey").regex(searchKey)), Company::class.java)


    fun mapList(): List<Company>? = mongoTemplate.findAll(Company::class.java)


    fun build(t: Company): String? {
        val keys = getSearchKeys(t)
        t.searchKey = if (keys.isNotEmpty()) {
            val first = utils.stringToPinyin(keys[0]!!, "first")
            val full = utils.stringToPinyin(keys[0]!!, "full")
            arrayOf(first.first(), first, full, *keys).distinct().joinToString(",")
        } else {
            ""
        }
        return t.searchKey
    }

    fun getSearchKeys(t: Company) = arrayOf(t.name!!, t.code)
}